// habit.js
import api from "../../config/api";
import { shareOptions } from "../../utils/access";
import request from "../../utils/request";
import { formatDate, getBarAndTitleHeight, getXsScreen, getStorage, setStorage, jump } from "../../utils/utils";
const app = getApp();

Page({
	data: {
		// 信号栏是否有背景
		hasBg: false,
		// 用户首页数据
		infoData: null,
		// 挑战状态
		challengeStatus: null,
		// 补救次数
		helpNum: null,
		// 补救任务个数
		helpTaskNum: null,
		// 补救日期
		helpDate: null,
		// 动画自动播放
		autoplay: false,
		// 第一层个数
		firstCount: 4,
		// 第一层选中项
		firstCurrent: 0,
		// 第二层选中项
		secondCurrent: 0,
		// 未登录信息
		noLoginInfo: {
			avatarUrl:
				"https://image-classify.daieco.com/kejian-quanzi/kzqO4t1WAPU8a5c42f9eea0da1235da0f38f2870620e.png",
			nickName: "未登录",
		},
		// 用户信息
		userInfo: {},
		// 球图片
		ballImagesMap: {
			normal: {
				// 知识
				learn: 'https://image-classify.daieco.com/kejian-quanzi/HSg9RMG92fg13c20f6f96054c17ade0a21705d7c8d01.png',
				// 测试
				test: 'https://image-classify.daieco.com/kejian-quanzi/qDIN5XLNVWxO669acf58a35e25c32f7e5ff6d873334b.png',
				// 成就
				medal: 'https://image-classify.daieco.com/kejian-quanzi/ETCdl0cf6WFUaa25031daab6bbe63ba09122f548208b.png',
				// 提醒
				warn: 'https://image-classify.daieco.com/kejian-quanzi/pgNRTtqZc75q5e0b676c3537aae92012ee80e4b97b13.png',
				// 圈子
				circle: 'https://image-classify.daieco.com/kejian-quanzi/X66yGzSvrBGkaa2ed4d7b744d699ed63939173685d90.png',
			},
			xs: {
				// 知识
				learn: 'https://image-classify.daieco.com/kejian-quanzi/4Z1EgMhhjveD2abfc8068397168289b81313692007c4.png',
				// 测试
				test: 'https://image-classify.daieco.com/kejian-quanzi/qxXdWTEFjpn8d8ca86a6ecc206df7403efe02852f5bd.png',
				// 成就
				medal: 'https://image-classify.daieco.com/kejian-quanzi/e7Oiv9A0d8srae4c47f06c2c89ddea5c2911d0ed7b26.png',
				// 提醒
				warn: 'https://image-classify.daieco.com/kejian-quanzi/pBSIyW9wAmeI4872692aca1fedab6898c4c12470c65a.png',
				// 圈子
				circle: 'https://image-classify.daieco.com/kejian-quanzi/oGpWu0Uhjvip8c9ad62d710719aeab70aaf6df0860da.png',
			},
		},
		// 球图片
		ballImages: {},
		// 是否是洼刘用户
		isWaliu: false,
		// 状态栏&标题栏高度
		...getBarAndTitleHeight(true),
		// 是否是小屏幕尺寸
		...getXsScreen(),
	},
	// 生命周期函数--监听页面加载
	onLoad(options) {
		const { isXsScreen, ballImagesMap } = this.data

		this.setData({
			...getBarAndTitleHeight(),
			ballImages: ballImagesMap[isXsScreen ? 'xs' : 'normal']
		})
	},

	// 生命周期函数--监听页面显示
	onShow() {
		const isLogin = app.isLogin()
		this.getUserData();
		// 获取用户是否是洼刘用户
		this.getWaliu()


		if (isLogin) {
			this.checkUserChallengeStatus();
		}

		this.setData({
			userInfo: isLogin ? app.userInfo() : this.data.noLoginInfo,
		})
	},
	// 动画切换
	swiperChange(e) {
		const { firstCount } = this.data

		if (e.detail.current === (firstCount - 1)) {
			setTimeout(() => {
				this.setData({
					autoplay: true,
				})
			}, 500)
		} else {
			setTimeout(() => {
				this.setData({
					secondCurrent: 0,
					autoplay: false,
				})
			}, 500)
		}
	},
	// 滑动项跳转
	swiperJump(e) {
		const { firstCount, firstCurrent } = this.data
		const type = e.currentTarget.dataset.type
		console.log(type, firstCurrent);
		// 向上翻
		if (type === 'prev') {
			const current = firstCurrent - 1
			this.setData({
				firstCurrent: current < 0 ? (firstCount - 1) : current
			})
		}
		// 向下翻
		if (type === 'next') {
			const current = firstCurrent + 1
			this.setData({
				firstCurrent: current >= firstCount ? 0 : current
			})
		}
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		this.modal = this.selectComponent('#modal')
	},
	// 页面相关事件处理函数--监听用户下拉动作
	onPullDownRefresh() {
		this.getUserData();
		wx.stopPullDownRefresh();
	},
	// 页面隐藏
	onHide() {
		setTimeout(() => {
			this.setData({
				firstCount: 4,
				firstCurrent: 0,
				secondCurrent: 0,
				autoplay: false,
			})
		}, 200)
	},
	// 获取用户是否是洼刘用户
	async getWaliu() {
		let isWaliu = false
		if (app.isLogin()) {
			// const res = await request.get(api.isWaliu, {}, { loading: false })
			const res = {
				httpStatus: 200,
				data: false
			}
			if (res?.httpStatus === 200) {
				isWaliu = res?.data
			}
		}
		this.setData({
			isWaliu
		})
	},
	// 获取首页数据
	async getUserData() {
		const userId = getStorage('userId')
		const res = await request.get(api.getDefaultData, { userId }, { loading: false })
		console.log(res,'====')
		const infoData = res?.data || {}
		let firstCount = 1

		if (infoData.insistClassifyNum) {
			firstCount = firstCount + 1
		}
		if (infoData.totalClassifyNum) {
			firstCount = firstCount + 1
		}
		if (infoData.carbonReductionTotalNums) {
			firstCount = firstCount + 1
		}

		// 碳减排数据处理
		if (infoData.carbonReductionTotalNums > 10000) {
			infoData.carbonIsKg = true
			infoData.carbonReductionTotalNums = (infoData.carbonReductionTotalNums / 1000).toFixed(1)
		}
		// 累计识别数据处理
		// if (infoData.totalRecognitionNum > 10000) {
		// 	infoData.recognitionIsWan = true
		// 	infoData.totalRecognitionNum = (infoData.totalRecognitionNum / 10000).toFixed(1)
		// }
		if (+infoData.totalRecognitionNum > 1000) {
			infoData.totalRecognitionNum = infoData.totalRecognitionNum.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
		}
		console.log('data', infoData);
		this.setData({
			infoData,
			firstCount,
			autoplay: firstCount === 1
		})
	},
	// 判断用户是否挑战失败
	async checkUserChallengeStatus() {
		const res = await request.get(api.checkIsFail, {}, { loading: false, modal: false });
		console.log("挑战状态", res);
		if (res.httpStatus == 200) {
			if ([0, 3].includes(res.data?.status)) {
				const activeContent = getStorage("activeContent") || {};
				const date = formatDate(new Date());
				if (activeContent.date != date) {
					const newActiveContent = { date };
					setStorage("activeContent", newActiveContent);

					this.setData({
						helpDate: res.data?.firstHelpDate,
						helpNum: res.data?.helpNum,
						helpTaskNum: res.data?.helpTaskNum,
						challengeStatus: res.data?.status,
					})

					this.modal.show()
				}
			}
		} else {
			this.setData({
				userInfo: {
					...this.data.noLoginInfo
				}
			})
		}
	},
	// 关闭弹窗
	clickDialogBtn: async function (e) {
		const { challengeStatus, helpDate } = this.data;
		// 去补救
		if (challengeStatus == 0) {
			e.detail.hide?.()
			wx.navigateTo({
				url: '/pages/trophy/trophy?date=' + (helpDate || ''),
			});
			return
		}
		// 开启挑战
		if ([3, 4].includes(challengeStatus)) {
			await request.get(api.startChallenge, null, { loading: false });
			wx.navigateTo({
				url: '/pages/trophy/trophy',
			})
		}
		e.detail.hide?.()
	},
	// 跳转需要登录页面
	async jumpPageNeedLogin(event) {
		const url = event.currentTarget.dataset.path
		if (app.isLogin()) {
			if (url) {
				jump(url)
			}
		} else {
			setStorage('redirectPath', '/pages/habit/habit')
			const userInfo = await app.login()

			if (app.isLogin()) {
				this.checkUserChallengeStatus()
				this.getUserData()
			}
			this.setData({
				userInfo,
			})
		}
	},
	// 跳转不需要登录页面
	jumpPageNoLogin(event) {
		const url = event.currentTarget.dataset.path
		if (url) {
			jump(url)
		}
	},
	// 页面滚动事件
	onPageScroll(e) {
		this.setData({
			hasBg: e?.scrollTop > 20,
		});
	},
	// 用户点击右上角分享
	onShareAppMessage(e) {
		return shareOptions('default', e)
	},
});
